package thread.多线程打印;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangjunfei
 * @date 2024/4/15 9:09
 */
public class 交替打印字符 {

    private int times = 50;

    private int state;

    private Lock reentrantLock = new ReentrantLock();


    private static final Object lock = new Object();


    private void Print(String printString, int threadNo) {
        for (int i = 0; i < times; ) {
            reentrantLock.lock();
            try {
                if (state % 3 == threadNo) {
                    i++;
                    System.out.println(printString);
                    state++;
                }
            } finally {
                reentrantLock.unlock();
            }
        }
    }


    private void notifyPrint(String pringString, int threadNo) {
        for (int i = 0; i < times; i++) {
            synchronized (lock) {
                if (state % 3 == threadNo) {
                    System.out.println(pringString);
                    state++;
                    lock.notifyAll();
                }else{
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                // while (state % 3 != threadNo) {
                //     try {
                //         lock.wait();
                //     } catch (InterruptedException e) {
                //         throw new RuntimeException(e);
                //     }
                // }

            }
        }
    }





    public static void main(String[] args) {
        交替打印字符 交替打印字符 = new 交替打印字符();
        // new Thread(()->{
        //     交替打印字符.Print("A",0);
        // }).start();
        // new Thread(()->{
        //     交替打印字符.Print("B",1);
        // }).start();
        // new Thread(()->{
        //     交替打印字符.Print("C",2);
        // }).start();


        new Thread(()->{
            交替打印字符.notifyPrint("A",0);
        }).start();
        new Thread(()->{
            交替打印字符.notifyPrint("B",1);
        }).start();
        new Thread(()->{
            交替打印字符.notifyPrint("C",2);
        }).start();
    }



}
